package com.servlet;

import com.service.UserService;
import com.util.Md5Util;
import com.util.SpringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String md5Password=null;

        UserService userService = SpringUtil.getBean(UserService.class);
        try {
            md5Password = Md5Util.toMd5(password);
        } catch (NoSuchAlgorithmException e) {
        }
        int i = userService.login(username, md5Password);

        if (i==1){
            req.getSession().setAttribute("username",username);
        }

        PrintWriter writer = resp.getWriter();
        writer.write(i+"");
        writer.close();
    }
}
